/*
 * Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.lang.invoke;


import java.util.*;

import static java.lang.invoke.MethodHandleStatics.*;

/**
 * 方法句柄是对底层方法、构造函数、字段或类似低级操作的类型化、直接可执行引用，
 * 可选择对参数或返回值进行转换。
 * 这些转换非常通用，包括诸如
 * {@linkplain #asType 转换}、
 * {@linkplain #bindTo 插入}、
 * {@linkplain java.lang.invoke.MethodHandles#dropArguments 删除}
 * 和{@linkplain java.lang.invoke.MethodHandles#filterArguments 替换}等模式。
 *
 * <h1>方法句柄内容</h1>
 * 方法句柄根据其参数和返回类型进行动态强类型化。
 * 它们不通过底层方法的名称或定义类来区分。
 * 方法句柄必须使用与方法句柄自身{@linkplain #type 类型描述符}匹配的
 * 符号类型描述符来调用。
 * <p>
 * 每个方法句柄通过{@link #type type}访问器报告其类型描述符。
 * 此类型描述符是一个{@link java.lang.invoke.MethodType MethodType}对象，
 * 其结构是一系列类，其中一个是方法的返回类型
 * （如果没有则为{@code void.class}）。
 * <p>
 * 方法句柄的类型控制它接受的调用类型，
 * 以及适用于它的转换种类。
 * <p>
 * 方法句柄包含一对特殊的调用器方法，
 * 称为{@link #invokeExact invokeExact}和{@link #invoke invoke}。
 * 两个调用器方法都提供对方法句柄底层方法、构造函数、字段或其他操作的直接访问，
 * 经过参数和返回值转换的修改。
 * 两个调用器都接受与方法句柄自身类型完全匹配的调用。
 * 普通的、不精确的调用器还接受一系列其他调用类型。
 * <p>
 * 方法句柄是不可变的，没有可见状态。
 * 当然，它们可以绑定到表现出状态的底层方法或数据。
 * 关于Java内存模型，任何方法句柄的行为都如同
 * 其所有（内部）字段都是final变量。这意味着任何对应用程序可见的方法句柄
 * 都将始终是完全形成的。
 * 即使方法句柄通过数据竞争中的共享变量发布，这也是成立的。
 * <p>
 * 方法句柄不能被用户子类化。
 * 实现可能（或可能不）创建{@code MethodHandle}的内部子类，
 * 这些子类可能通过{@link java.lang.Object#getClass Object.getClass}
 * 操作可见。程序员不应该从方法句柄的特定类得出结论，
 * 因为方法句柄类层次结构（如果有的话）
 * 可能会不时变化或在不同供应商的实现之间变化。
 *
 * <h1>方法句柄编译</h1>
 * 命名{@code invokeExact}或{@code invoke}的Java方法调用表达式
 * 可以从Java源代码调用方法句柄。
 * 从源代码的角度来看，这些方法可以接受任何参数
 * 并且其结果可以转换为任何返回类型。
 * 形式上，这是通过给调用器方法
 * {@code Object}返回类型和可变参数{@code Object}参数来实现的，
 * 但它们有一个称为<em>签名多态性</em>的附加特性，
 * 它将这种调用自由度直接连接到JVM执行栈。
 * <p>
 * 与虚方法通常一样，对{@code invokeExact}
 * 和{@code invoke}的源级调用编译为{@code invokevirtual}指令。
 * 更不寻常的是，编译器必须记录实际参数类型，
 * 并且不能对参数执行方法调用转换。
 * 相反，它必须根据它们自己的未转换类型将它们推送到栈上。
 * 方法句柄对象本身在参数之前被推送到栈上。
 * 然后编译器使用描述参数和返回类型的符号类型描述符
 * 调用方法句柄。
 * <p>
 * 要发出完整的符号类型描述符，编译器还必须确定
 * 返回类型。这基于方法调用表达式上的转换（如果有的话），
 * 或者如果调用是表达式则为{@code Object}，
 * 或者如果调用是语句则为{@code void}。
 * 转换可能是原始类型（但不是{@code void}）。
 * <p>
 * 作为特殊情况，未转换的{@code null}参数被给予
 * {@code java.lang.Void}的符号类型描述符。
 * 与类型{@code Void}的歧义是无害的，因为除了null引用之外
 * 没有{@code Void}类型的引用。
 *
 * <h1>方法句柄调用</h1>
 * 第一次执行{@code invokevirtual}指令时，
 * 它通过符号解析指令中的名称并验证方法调用在静态上是合法的来进行链接。
 * 对{@code invokeExact}和{@code invoke}的调用也是如此。
 * 在这种情况下，编译器发出的符号类型描述符会被检查
 * 语法正确性，并解析其包含的名称。
 * 因此，调用方法句柄的{@code invokevirtual}指令总是会链接，
 * 只要符号类型描述符在语法上是良好形式的
 * 并且类型存在。
 * <p>
 * 当{@code invokevirtual}在链接后执行时，
 * JVM首先检查接收方法句柄的类型
 * 以确保它与符号类型描述符匹配。
 * 如果类型匹配失败，这意味着调用者正在调用的方法
 * 在被调用的单个方法句柄上不存在。
 * <p>
 * 在{@code invokeExact}的情况下，调用的类型描述符
 * （在解析符号类型名称后）必须与接收方法句柄的方法类型完全匹配。
 * 在普通的、不精确的{@code invoke}的情况下，解析的类型描述符
 * 必须是接收者的{@link #asType asType}方法的有效参数。
 * 因此，普通的{@code invoke}比{@code invokeExact}更宽松。
 * <p>
 * 在类型匹配后，对{@code invokeExact}的调用直接
 * 并立即调用方法句柄的底层方法
 * （或其他行为，视情况而定）。
 * <p>
 * 对普通{@code invoke}的调用与对{@code invokeExact}的调用工作方式相同，
 * 如果调用者指定的符号类型描述符
 * 与方法句柄自身的类型完全匹配。
 * 如果存在类型不匹配，{@code invoke}尝试
 * 调整接收方法句柄的类型，
 * 就像通过调用{@link #asType asType}一样，
 * 以获得一个可精确调用的方法句柄{@code M2}。
 * 这允许调用者和被调用者之间进行更强大的方法类型协商。
 * <p>
 * （<em>注意：</em>调整后的方法句柄{@code M2}不是直接可观察的，
 * 因此实现不需要将其物化。）
 *
 * <h1>调用检查</h1>
 * 在典型程序中，方法句柄类型匹配通常会成功。
 * 但如果匹配失败，JVM将抛出{@link WrongMethodTypeException}，
 * 要么直接抛出（在{@code invokeExact}的情况下），要么间接抛出，
 * 就像调用{@code asType}失败一样（在{@code invoke}的情况下）。
 * <p>
 * 因此，在静态类型程序中可能显示为链接错误的方法类型不匹配
 * 在使用方法句柄的程序中可能显示为
 * 动态{@code WrongMethodTypeException}。
 * <p>
 * 因为方法类型包含"活的"{@code Class}对象，
 * 方法类型匹配会考虑类型名称和类加载器。
 * 因此，即使方法句柄{@code M}在一个类加载器{@code L1}中创建
 * 并在另一个类加载器{@code L2}中使用，
 * 方法句柄调用也是类型安全的，因为调用者的符号类型描述符
 * （在{@code L2}中解析）
 * 与原始被调用方法的符号类型描述符（在{@code L1}中解析）进行匹配。
 * 在{@code L1}中的解析发生在创建{@code M}并分配其类型时，
 * 而在{@code L2}中的解析发生在链接{@code invokevirtual}指令时。
 * <p>
 * 除了类型描述符的检查之外，
 * 方法句柄调用其底层方法的能力是不受限制的。
 * 如果方法句柄是由有权访问非公共方法的类在该方法上形成的，
 * 那么任何接收到该句柄引用的调用者都可以在任何地方使用生成的句柄。
 * <p>
 * 与核心反射API不同（在核心反射API中，每次调用反射方法时都会检查访问权限），
 * 方法句柄访问检查是在
 * <a href="MethodHandles.Lookup.html#access">创建方法句柄时</a>执行的。
 * 在{@code ldc}的情况下（见下文），访问检查作为链接
 * 常量方法句柄底层常量池条目的一部分执行。
 * <p>
 * 因此，对非公共方法或非公共类中方法的句柄
 * 通常应该保密。
 * 除非不受信任代码使用它们是无害的，否则不应将它们传递给不受信任的代码。
 *
 * <h1>方法句柄创建</h1>
 * Java代码可以创建直接访问该代码可访问的
 * 任何方法、构造函数或字段的方法句柄。
 * 这通过一个基于反射和能力的API来完成，称为
 * {@link java.lang.invoke.MethodHandles.Lookup MethodHandles.Lookup}。
 * 例如，可以从{@link java.lang.invoke.MethodHandles.Lookup#findStatic Lookup.findStatic}
 * 获得静态方法句柄。
 * 还有从核心反射API对象转换的方法，
 * 如{@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}。
 * <p>
 * 像类和字符串一样，对应于可访问字段、方法和构造函数的方法句柄
 * 也可以直接在类文件的常量池中表示为
 * 由{@code ldc}字节码加载的常量。
 * 一种新的常量池条目类型{@code CONSTANT_MethodHandle}
 * 直接引用关联的{@code CONSTANT_Methodref}、
 * {@code CONSTANT_InterfaceMethodref}或{@code CONSTANT_Fieldref}
 * 常量池条目。
 * （有关方法句柄常量的完整详细信息，
 * 请参见Java虚拟机规范的4.4.8和5.4.3.5节。）
 * <p>
 * 通过查找或从带有可变参数修饰符位（{@code 0x0080}）的方法或构造函数
 * 进行常量加载产生的方法句柄具有相应的可变参数，
 * 就像它们是在{@link #asVarargsCollector asVarargsCollector}的帮助下定义的一样。
 * <p>
 * 方法引用可以引用静态或非静态方法。
 * 在非静态情况下，方法句柄类型包括一个显式的接收者参数，
 * 在任何其他参数之前添加。
 * 在方法句柄的类型中，初始接收者参数根据
 * 最初请求该方法的类进行类型化。
 * （例如，如果通过{@code ldc}获得非静态方法句柄，
 * 接收者的类型是常量池条目中命名的类。）
 * <p>
 * 方法句柄常量受到与其对应字节码指令相同的链接时访问检查，
 * 如果字节码行为会抛出此类错误，{@code ldc}指令
 * 将抛出相应的链接错误。
 * <p>
 * 作为这一点的推论，对受保护成员的访问仅限于
 * 访问类或其子类之一的接收者，
 * 并且访问类必须反过来是受保护成员定义类的子类（或包兄弟）。
 * 如果方法引用引用当前包外类的受保护非静态方法或字段，
 * 接收者参数将被缩小为访问类的类型。
 * <p>
 * 当调用虚方法的方法句柄时，
 * 总是在接收者（即第一个参数）中查找该方法。
 * <p>
 * 也可以创建特定虚方法实现的非虚方法句柄。
 * 这些不基于接收者类型执行虚查找。
 * 这样的方法句柄模拟对同一方法的{@code invokespecial}指令的效果。
 *
 * <h1>使用示例</h1>
 * 以下是一些使用示例：
 * <blockquote><pre>{@code
Object x, y; String s; int i;
MethodType mt; MethodHandle mh;
MethodHandles.Lookup lookup = MethodHandles.lookup();
// mt是(char,char)String
mt = MethodType.methodType(String.class, char.class, char.class);
mh = lookup.findVirtual(String.class, "replace", mt);
s = (String) mh.invokeExact("daddy",'d','n');
// invokeExact(Ljava/lang/String;CC)Ljava/lang/String;
assertEquals(s, "nanny");
// 弱类型调用（使用MHs.invoke）
s = (String) mh.invokeWithArguments("sappy", 'p', 'v');
assertEquals(s, "savvy");
// mt是(Object[])List
mt = MethodType.methodType(java.util.List.class, Object[].class);
mh = lookup.findStatic(java.util.Arrays.class, "asList", mt);
assert(mh.isVarargsCollector());
x = mh.invoke("one", "two");
// invoke(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;
assertEquals(x, java.util.Arrays.asList("one","two"));
// mt是(Object,Object,Object)Object
mt = MethodType.genericMethodType(3);
mh = mh.asType(mt);
x = mh.invokeExact((Object)1, (Object)2, (Object)3);
// invokeExact(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
assertEquals(x, java.util.Arrays.asList(1,2,3));
// mt是()int
mt = MethodType.methodType(int.class);
mh = lookup.findVirtual(java.util.List.class, "size", mt);
i = (int) mh.invokeExact(java.util.Arrays.asList(1,2,3));
// invokeExact(Ljava/util/List;)I
assert(i == 3);
mt = MethodType.methodType(void.class, String.class);
mh = lookup.findVirtual(java.io.PrintStream.class, "println", mt);
mh.invokeExact(System.out, "Hello, world.");
// invokeExact(Ljava/io/PrintStream;Ljava/lang/String;)V
 * }</pre></blockquote>
 * 上述每个对{@code invokeExact}或普通{@code invoke}的调用
 * 都生成一个带有后续注释中指示的符号类型描述符的
 * 单个invokevirtual指令。
 * 在这些示例中，假设辅助方法{@code assertEquals}
 * 是一个在其参数上调用{@link java.util.Objects#equals(Object,Object) Objects.equals}
 * 并断言结果为true的方法。
 *
 * <h1>异常</h1>
 * 方法{@code invokeExact}和{@code invoke}被声明为
 * 抛出{@link java.lang.Throwable Throwable}，
 * 这意味着对方法句柄可以抛出什么没有静态限制。
 * 由于JVM不区分受检异常和非受检异常（当然，除了通过它们的类），
 * 将受检异常归因于方法句柄调用对字节码形状没有特殊影响。
 * 但在Java源代码中，执行方法句柄调用的方法必须
 * 要么显式抛出{@code Throwable}，
 * 要么必须在本地捕获所有可抛出对象，
 * 只重新抛出在上下文中合法的那些，并包装非法的那些。
 *
 * <h1><a name="sigpoly"></a>签名多态性</h1>
 * {@code invokeExact}和普通{@code invoke}的
 * 不寻常编译和链接行为
 * 被术语<em>签名多态性</em>所引用。
 * 如Java语言规范中定义的，
 * 签名多态方法是可以与
 * 广泛范围的调用签名和返回类型一起操作的方法。
 * <p>
 * 在源代码中，对签名多态方法的调用将会编译，
 * 无论请求的符号类型描述符如何。
 * 像往常一样，Java编译器发出一个{@code invokevirtual}指令，
 * 针对命名方法使用给定的符号类型描述符。
 * 不寻常的部分是符号类型描述符是从
 * 实际参数和返回类型派生的，而不是从方法声明派生的。
 * <p>
 * 当JVM处理包含签名多态调用的字节码时，
 * 它将成功链接任何此类调用，无论其符号类型描述符如何。
 * （为了保持类型安全，JVM将使用适当的
 * 动态类型检查来保护此类调用，如其他地方所述。）
 * <p>
 * 字节码生成器，包括编译器后端，需要为这些方法
 * 发出未转换的符号类型描述符。
 * 确定符号链接的工具需要接受此类
 * 未转换的描述符，而不报告链接错误。
 *
 * <h1>方法句柄与核心反射API之间的互操作</h1>
 * 使用{@link java.lang.invoke.MethodHandles.Lookup Lookup} API中的工厂方法，
 * 任何由核心反射API对象表示的类成员
 * 都可以转换为行为等效的方法句柄。
 * 例如，反射{@link java.lang.reflect.Method Method}可以
 * 使用{@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}
 * 转换为方法句柄。
 * 生成的方法句柄通常提供对底层类成员
 * 更直接和高效的访问。
 * <p>
 * 作为特殊情况，
 * 当使用核心反射API查看此类中的签名多态方法
 * {@code invokeExact}或普通{@code invoke}时，
 * 它们显示为普通的非多态方法。
 * 它们的反射外观，如
 * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod}所查看的，
 * 不受它们在此API中的特殊状态影响。
 * 例如，{@link java.lang.reflect.Method#getModifiers Method.getModifiers}
 * 将报告任何类似声明方法所需的确切修饰符位，
 * 在这种情况下包括{@code native}和{@code varargs}位。
 * <p>
 * 与任何反射方法一样，这些方法（当被反射时）可以
 * 通过{@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}调用。
 * 但是，此类反射调用不会导致方法句柄调用。
 * 如果传递所需参数（单个{@code Object[]}类型的参数），
 * 此类调用将忽略参数并抛出{@code UnsupportedOperationException}。
 * <p>
 * 由于{@code invokevirtual}指令可以在任何符号类型描述符下
 * 本地调用方法句柄，这种反射视图与
 * 通过字节码正常呈现这些方法冲突。
 * 因此，当通过{@code Class.getDeclaredMethod}反射查看时，
 * 这两个本地方法可能仅被视为占位符。
 * <p>
 * 为了获得特定类型描述符的调用器方法，
 * 使用{@link java.lang.invoke.MethodHandles#exactInvoker MethodHandles.exactInvoker}
 * 或{@link java.lang.invoke.MethodHandles#invoker MethodHandles.invoker}。
 * {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
 * API也能够返回一个方法句柄
 * 来调用{@code invokeExact}或普通{@code invoke}，
 * 对于任何指定的类型描述符。
 *
 * <h1>方法句柄与Java泛型之间的互操作</h1>
 * 可以在使用Java泛型类型声明的方法、构造函数或字段上
 * 获得方法句柄。
 * 与核心反射API一样，方法句柄的类型
 * 将从源级类型的擦除构造。
 * 当调用方法句柄时，其参数的类型
 * 或返回值转换类型可能是泛型类型或类型实例。
 * 如果发生这种情况，编译器在为{@code invokevirtual}指令
 * 构造符号类型描述符时
 * 将用它们的擦除替换这些类型。
 * <p>
 * 方法句柄不以Java参数化（泛型）类型的形式
 * 表示它们的函数式类型，
 * 因为函数式类型和参数化Java类型之间存在三个不匹配。
 * <ul>
 * <li>方法类型涵盖所有可能的参数数量，
 * 从无参数到<a href="MethodHandle.html#maxarity">最大允许参数数量</a>。
 * 泛型不是可变参数的，因此无法表示这一点。</li>
 * <li>方法类型可以指定原始类型的参数，
 * 而Java泛型类型无法涵盖这些。</li>
 * <li>方法句柄上的高阶函数（组合器）
 * 通常在广泛的函数类型范围内是泛型的，包括
 * 多种参数数量的函数类型。用Java类型参数
 * 表示这种泛型性是不可能的。</li>
 * </ul>
 *
 * <h1><a name="maxarity"></a>参数数量限制</h1>
 * JVM对所有类型的方法和构造函数施加
 * 255个堆栈参数的绝对限制。在某些情况下，此限制可能显得更加严格：
 * <ul>
 * <li>{@code long}或{@code double}参数（就参数数量限制而言）计为两个参数槽。
 * <li>非静态方法为调用该方法的对象消耗一个额外参数。
 * <li>构造函数为正在构造的对象消耗一个额外参数。
 * <li>由于方法句柄的{@code invoke}方法（或其他签名多态方法）是非虚拟的，
 *     除了任何非虚拟接收者对象外，它还为方法句柄本身消耗一个额外参数。
 * </ul>
 * 这些限制意味着某些方法句柄无法创建，仅仅因为JVM对堆栈参数的限制。
 * 例如，如果静态JVM方法恰好接受255个参数，则无法为其创建方法句柄。
 * 尝试创建具有不可能方法类型的方法句柄会导致{@link IllegalArgumentException}。
 * 特别是，方法句柄的类型不得具有确切最大值255的参数数量。
 *
 * @see MethodType
 * @see MethodHandles
 * @author John Rose, JSR 292 EG
 */
public abstract class MethodHandle {
    static { MethodHandleImpl.initStatics(); }

    /**
     * 内部标记接口，用于区分（对Java编译器而言）
     * 那些<a href="MethodHandle.html#sigpoly">签名多态</a>的方法。
     */
    @java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
    @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
    @interface PolymorphicSignature { }

    private final MethodType type;
    /*private*/ final LambdaForm form;
    // form不是私有的，以便调用器可以轻松获取它
    /*private*/ MethodHandle asTypeCache;
    // asTypeCache不是私有的，以便调用器可以轻松获取它
    /*non-public*/ byte customizationCount;
    // customizationCount应该可以从调用器访问

    /**
     * 报告此方法句柄的类型。
     * 通过{@code invokeExact}对此方法句柄的每次调用都必须与此类型完全匹配。
     * @return 方法句柄类型
     */
    public MethodType type() {
        return type;
    }

    /**
     * 方法句柄实现层次结构的包私有构造函数。
     * 方法句柄继承将完全包含在
     * {@code java.lang.invoke}包内。
     */
    // @param type 新方法句柄的类型（永久分配）
    /*non-public*/ MethodHandle(MethodType type, LambdaForm form) {
        type.getClass();  // explicit NPE
        form.getClass();  // explicit NPE
        this.type = type;
        this.form = form.uncustomize();

        this.form.prepare();  // 待办：尝试将此步骤延迟到调用之前。
    }

    /**
     * 调用方法句柄，允许任何调用者类型描述符，但要求精确的类型匹配。
     * {@code invokeExact}调用站点的符号类型描述符必须
     * 与此方法句柄的{@link #type type}完全匹配。
     * 不允许对参数或返回值进行转换。
     * <p>
     * 当通过核心反射API观察此方法时，
     * 它将显示为单个本地方法，接受对象数组并返回对象。
     * 如果通过{@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}、
     * 通过JNI或间接通过{@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}
     * 直接调用此本地方法，
     * 它将抛出{@code UnsupportedOperationException}。
     * @param args 签名多态参数列表，使用varargs静态表示
     * @return 签名多态结果，使用{@code Object}静态表示
     * @throws WrongMethodTypeException 如果目标的类型与调用者的符号类型描述符不相同
     * @throws Throwable 底层方法抛出的任何异常都会通过方法句柄调用不变地传播
     */
    public final native @PolymorphicSignature Object invokeExact(Object... args) throws Throwable;

    /**
     * Invokes the method handle, allowing any caller type descriptor,
     * and optionally performing conversions on arguments and return values.
     * <p>
     * If the call site's symbolic type descriptor exactly matches this method handle's {@link #type type},
     * the call proceeds as if by {@link #invokeExact invokeExact}.
     * <p>
     * Otherwise, the call proceeds as if this method handle were first
     * adjusted by calling {@link #asType asType} to adjust this method handle
     * to the required type, and then the call proceeds as if by
     * {@link #invokeExact invokeExact} on the adjusted method handle.
     * <p>
     * There is no guarantee that the {@code asType} call is actually made.
     * If the JVM can predict the results of making the call, it may perform
     * adaptations directly on the caller's arguments,
     * and call the target method handle according to its own exact type.
     * <p>
     * The resolved type descriptor at the call site of {@code invoke} must
     * be a valid argument to the receivers {@code asType} method.
     * In particular, the caller must specify the same argument arity
     * as the callee's type,
     * if the callee is not a {@linkplain #asVarargsCollector variable arity collector}.
     * <p>
     * When this method is observed via the Core Reflection API,
     * it will appear as a single native method, taking an object array and returning an object.
     * If this native method is invoked directly via
     * {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}, via JNI,
     * or indirectly via {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect},
     * it will throw an {@code UnsupportedOperationException}.
     * @param args the signature-polymorphic parameter list, statically represented using varargs
     * @return the signature-polymorphic result, statically represented using {@code Object}
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to the caller's symbolic type descriptor
     * @throws ClassCastException if the target's type can be adjusted to the caller, but a reference cast fails
     * @throws Throwable anything thrown by the underlying method propagates unchanged through the method handle call
     */
    public final native @PolymorphicSignature Object invoke(Object... args) throws Throwable;

    /**
     * Private method for trusted invocation of a method handle respecting simplified signatures.
     * Type mismatches will not throw {@code WrongMethodTypeException}, but could crash the JVM.
     * <p>
     * The caller signature is restricted to the following basic types:
     * Object, int, long, float, double, and void return.
     * <p>
     * The caller is responsible for maintaining type correctness by ensuring
     * that the each outgoing argument value is a member of the range of the corresponding
     * callee argument type.
     * (The caller should therefore issue appropriate casts and integer narrowing
     * operations on outgoing argument values.)
     * The caller can assume that the incoming result value is part of the range
     * of the callee's return type.
     * @param args the signature-polymorphic parameter list, statically represented using varargs
     * @return the signature-polymorphic result, statically represented using {@code Object}
     */
    /*non-public*/ final native @PolymorphicSignature Object invokeBasic(Object... args) throws Throwable;

    /**
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeVirtual}.
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
     * The trailing (not leading) argument must be a MemberName.
     * @param args the signature-polymorphic parameter list, statically represented using varargs
     * @return the signature-polymorphic result, statically represented using {@code Object}
     */
    /*non-public*/ static native @PolymorphicSignature Object linkToVirtual(Object... args) throws Throwable;

    /**
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeStatic}.
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
     * The trailing (not leading) argument must be a MemberName.
     * @param args the signature-polymorphic parameter list, statically represented using varargs
     * @return the signature-polymorphic result, statically represented using {@code Object}
     */
    /*non-public*/ static native @PolymorphicSignature Object linkToStatic(Object... args) throws Throwable;

    /**
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeSpecial}.
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
     * The trailing (not leading) argument must be a MemberName.
     * @param args the signature-polymorphic parameter list, statically represented using varargs
     * @return the signature-polymorphic result, statically represented using {@code Object}
     */
    /*non-public*/ static native @PolymorphicSignature Object linkToSpecial(Object... args) throws Throwable;

    /**
     * Private method for trusted invocation of a MemberName of kind {@code REF_invokeInterface}.
     * The caller signature is restricted to basic types as with {@code invokeBasic}.
     * The trailing (not leading) argument must be a MemberName.
     * @param args the signature-polymorphic parameter list, statically represented using varargs
     * @return the signature-polymorphic result, statically represented using {@code Object}
     */
    /*non-public*/ static native @PolymorphicSignature Object linkToInterface(Object... args) throws Throwable;

    /**
     * Performs a variable arity invocation, passing the arguments in the given list
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
     * which mentions only the type {@code Object}, and whose arity is the length
     * of the argument list.
     * <p>
     * Specifically, execution proceeds as if by the following steps,
     * although the methods are not guaranteed to be called if the JVM
     * can predict their effects.
     * <ul>
     * <li>Determine the length of the argument array as {@code N}.
     *     For a null reference, {@code N=0}. </li>
     * <li>Determine the general type {@code TN} of {@code N} arguments as
     *     as {@code TN=MethodType.genericMethodType(N)}.</li>
     * <li>Force the original target method handle {@code MH0} to the
     *     required type, as {@code MH1 = MH0.asType(TN)}. </li>
     * <li>Spread the array into {@code N} separate arguments {@code A0, ...}. </li>
     * <li>Invoke the type-adjusted method handle on the unpacked arguments:
     *     MH1.invokeExact(A0, ...). </li>
     * <li>Take the return value as an {@code Object} reference. </li>
     * </ul>
     * <p>
     * Because of the action of the {@code asType} step, the following argument
     * conversions are applied as necessary:
     * <ul>
     * <li>reference casting
     * <li>unboxing
     * <li>widening primitive conversions
     * </ul>
     * <p>
     * The result returned by the call is boxed if it is a primitive,
     * or forced to null if the return type is void.
     * <p>
     * This call is equivalent to the following code:
     * <blockquote><pre>{@code
     * MethodHandle invoker = MethodHandles.spreadInvoker(this.type(), 0);
     * Object result = invoker.invokeExact(this, arguments);
     * }</pre></blockquote>
     * <p>
     * Unlike the signature polymorphic methods {@code invokeExact} and {@code invoke},
     * {@code invokeWithArguments} can be accessed normally via the Core Reflection API and JNI.
     * It can therefore be used as a bridge between native or reflective code and method handles.
     *
     * @param arguments the arguments to pass to the target
     * @return the result returned by the target
     * @throws ClassCastException if an argument cannot be converted by reference casting
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
     * @throws Throwable anything thrown by the target method invocation
     * @see MethodHandles#spreadInvoker
     */
    public Object invokeWithArguments(Object... arguments) throws Throwable {
        MethodType invocationType = MethodType.genericMethodType(arguments == null ? 0 : arguments.length);
        return invocationType.invokers().spreadInvoker(0).invokeExact(asType(invocationType), arguments);
    }

    /**
     * Performs a variable arity invocation, passing the arguments in the given array
     * to the method handle, as if via an inexact {@link #invoke invoke} from a call site
     * which mentions only the type {@code Object}, and whose arity is the length
     * of the argument array.
     * <p>
     * This method is also equivalent to the following code:
     * <blockquote><pre>{@code
     *   invokeWithArguments(arguments.toArray()
     * }</pre></blockquote>
     *
     * @param arguments the arguments to pass to the target
     * @return the result returned by the target
     * @throws NullPointerException if {@code arguments} is a null reference
     * @throws ClassCastException if an argument cannot be converted by reference casting
     * @throws WrongMethodTypeException if the target's type cannot be adjusted to take the given number of {@code Object} arguments
     * @throws Throwable anything thrown by the target method invocation
     */
    public Object invokeWithArguments(java.util.List<?> arguments) throws Throwable {
        return invokeWithArguments(arguments.toArray());
    }

    /**
     * Produces an adapter method handle which adapts the type of the
     * current method handle to a new type.
     * The resulting method handle is guaranteed to report a type
     * which is equal to the desired new type.
     * <p>
     * If the original type and new type are equal, returns {@code this}.
     * <p>
     * The new method handle, when invoked, will perform the following
     * steps:
     * <ul>
     * <li>Convert the incoming argument list to match the original
     *     method handle's argument list.
     * <li>Invoke the original method handle on the converted argument list.
     * <li>Convert any result returned by the original method handle
     *     to the return type of new method handle.
     * </ul>
     * <p>
     * This method provides the crucial behavioral difference between
     * {@link #invokeExact invokeExact} and plain, inexact {@link #invoke invoke}.
     * The two methods
     * perform the same steps when the caller's type descriptor exactly m atches
     * the callee's, but when the types differ, plain {@link #invoke invoke}
     * also calls {@code asType} (or some internal equivalent) in order
     * to match up the caller's and callee's types.
     * <p>
     * If the current method is a variable arity method handle
     * argument list conversion may involve the conversion and collection
     * of several arguments into an array, as
     * {@linkplain #asVarargsCollector described elsewhere}.
     * In every other case, all conversions are applied <em>pairwise</em>,
     * which means that each argument or return value is converted to
     * exactly one argument or return value (or no return value).
     * The applied conversions are defined by consulting the
     * the corresponding component types of the old and new
     * method handle types.
     * <p>
     * Let <em>T0</em> and <em>T1</em> be corresponding new and old parameter types,
     * or old and new return types.  Specifically, for some valid index {@code i}, let
     * <em>T0</em>{@code =newType.parameterType(i)} and <em>T1</em>{@code =this.type().parameterType(i)}.
     * Or else, going the other way for return values, let
     * <em>T0</em>{@code =this.type().returnType()} and <em>T1</em>{@code =newType.returnType()}.
     * If the types are the same, the new method handle makes no change
     * to the corresponding argument or return value (if any).
     * Otherwise, one of the following conversions is applied
     * if possible:
     * <ul>
     * <li>If <em>T0</em> and <em>T1</em> are references, then a cast to <em>T1</em> is applied.
     *     (The types do not need to be related in any particular way.
     *     This is because a dynamic value of null can convert to any reference type.)
     * <li>If <em>T0</em> and <em>T1</em> are primitives, then a Java method invocation
     *     conversion (JLS 5.3) is applied, if one exists.
     *     (Specifically, <em>T0</em> must convert to <em>T1</em> by a widening primitive conversion.)
     * <li>If <em>T0</em> is a primitive and <em>T1</em> a reference,
     *     a Java casting conversion (JLS 5.5) is applied if one exists.
     *     (Specifically, the value is boxed from <em>T0</em> to its wrapper class,
     *     which is then widened as needed to <em>T1</em>.)
     * <li>If <em>T0</em> is a reference and <em>T1</em> a primitive, an unboxing
     *     conversion will be applied at runtime, possibly followed
     *     by a Java method invocation conversion (JLS 5.3)
     *     on the primitive value.  (These are the primitive widening conversions.)
     *     <em>T0</em> must be a wrapper class or a supertype of one.
     *     (In the case where <em>T0</em> is Object, these are the conversions
     *     allowed by {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke}.)
     *     The unboxing conversion must have a possibility of success, which means that
     *     if <em>T0</em> is not itself a wrapper class, there must exist at least one
     *     wrapper class <em>TW</em> which is a subtype of <em>T0</em> and whose unboxed
     *     primitive value can be widened to <em>T1</em>.
     * <li>If the return type <em>T1</em> is marked as void, any returned value is discarded
     * <li>If the return type <em>T0</em> is void and <em>T1</em> a reference, a null value is introduced.
     * <li>If the return type <em>T0</em> is void and <em>T1</em> a primitive,
     *     a zero value is introduced.
     * </ul>
     * (<em>Note:</em> Both <em>T0</em> and <em>T1</em> may be regarded as static types,
     * because neither corresponds specifically to the <em>dynamic type</em> of any
     * actual argument or return value.)
     * <p>
     * The method handle conversion cannot be made if any one of the required
     * pairwise conversions cannot be made.
     * <p>
     * At runtime, the conversions applied to reference arguments
     * or return values may require additional runtime checks which can fail.
     * An unboxing operation may fail because the original reference is null,
     * causing a {@link java.lang.NullPointerException NullPointerException}.
     * An unboxing operation or a reference cast may also fail on a reference
     * to an object of the wrong type,
     * causing a {@link java.lang.ClassCastException ClassCastException}.
     * Although an unboxing operation may accept several kinds of wrappers,
     * if none are available, a {@code ClassCastException} will be thrown.
     *
     * @param newType the expected type of the new method handle
     * @return a method handle which delegates to {@code this} after performing
     *           any necessary argument conversions, and arranges for any
     *           necessary return value conversions
     * @throws NullPointerException if {@code newType} is a null reference
     * @throws WrongMethodTypeException if the conversion cannot be made
     * @see MethodHandles#explicitCastArguments
     */
    public MethodHandle asType(MethodType newType) {
        // Fast path alternative to a heavyweight {@code asType} call.
        // Return 'this' if the conversion will be a no-op.
        if (newType == type) {
            return this;
        }
        // Return 'this.asTypeCache' if the conversion is already memoized.
        MethodHandle atc = asTypeCached(newType);
        if (atc != null) {
            return atc;
        }
        return asTypeUncached(newType);
    }

    private MethodHandle asTypeCached(MethodType newType) {
        MethodHandle atc = asTypeCache;
        if (atc != null && newType == atc.type) {
            return atc;
        }
        return null;
    }

    /** Override this to change asType behavior. */
    /*non-public*/ MethodHandle asTypeUncached(MethodType newType) {
        if (!type.isConvertibleTo(newType))
            throw new WrongMethodTypeException("cannot convert "+this+" to "+newType);
        return asTypeCache = MethodHandleImpl.makePairwiseConvert(this, newType, true);
    }

    /**
     * Makes an <em>array-spreading</em> method handle, which accepts a trailing array argument
     * and spreads its elements as positional arguments.
     * The new method handle adapts, as its <i>target</i>,
     * the current method handle.  The type of the adapter will be
     * the same as the type of the target, except that the final
     * {@code arrayLength} parameters of the target's type are replaced
     * by a single array parameter of type {@code arrayType}.
     * <p>
     * If the array element type differs from any of the corresponding
     * argument types on the original target,
     * the original target is adapted to take the array elements directly,
     * as if by a call to {@link #asType asType}.
     * <p>
     * When called, the adapter replaces a trailing array argument
     * by the array's elements, each as its own argument to the target.
     * (The order of the arguments is preserved.)
     * They are converted pairwise by casting and/or unboxing
     * to the types of the trailing parameters of the target.
     * Finally the target is called.
     * What the target eventually returns is returned unchanged by the adapter.
     * <p>
     * Before calling the target, the adapter verifies that the array
     * contains exactly enough elements to provide a correct argument count
     * to the target method handle.
     * (The array may also be null when zero elements are required.)
     * <p>
     * If, when the adapter is called, the supplied array argument does
     * not have the correct number of elements, the adapter will throw
     * an {@link IllegalArgumentException} instead of invoking the target.
     * <p>
     * Here are some simple examples of array-spreading method handles:
     * <blockquote><pre>{@code
MethodHandle equals = publicLookup()
  .findVirtual(String.class, "equals", methodType(boolean.class, Object.class));
assert( (boolean) equals.invokeExact("me", (Object)"me"));
assert(!(boolean) equals.invokeExact("me", (Object)"thee"));
// spread both arguments from a 2-array:
MethodHandle eq2 = equals.asSpreader(Object[].class, 2);
assert( (boolean) eq2.invokeExact(new Object[]{ "me", "me" }));
assert(!(boolean) eq2.invokeExact(new Object[]{ "me", "thee" }));
// try to spread from anything but a 2-array:
for (int n = 0; n <= 10; n++) {
  Object[] badArityArgs = (n == 2 ? null : new Object[n]);
  try { assert((boolean) eq2.invokeExact(badArityArgs) && false); }
  catch (IllegalArgumentException ex) { } // OK
}
// spread both arguments from a String array:
MethodHandle eq2s = equals.asSpreader(String[].class, 2);
assert( (boolean) eq2s.invokeExact(new String[]{ "me", "me" }));
assert(!(boolean) eq2s.invokeExact(new String[]{ "me", "thee" }));
// spread second arguments from a 1-array:
MethodHandle eq1 = equals.asSpreader(Object[].class, 1);
assert( (boolean) eq1.invokeExact("me", new Object[]{ "me" }));
assert(!(boolean) eq1.invokeExact("me", new Object[]{ "thee" }));
// spread no arguments from a 0-array or null:
MethodHandle eq0 = equals.asSpreader(Object[].class, 0);
assert( (boolean) eq0.invokeExact("me", (Object)"me", new Object[0]));
assert(!(boolean) eq0.invokeExact("me", (Object)"thee", (Object[])null));
// asSpreader and asCollector are approximate inverses:
for (int n = 0; n <= 2; n++) {
    for (Class<?> a : new Class<?>[]{Object[].class, String[].class, CharSequence[].class}) {
        MethodHandle equals2 = equals.asSpreader(a, n).asCollector(a, n);
        assert( (boolean) equals2.invokeWithArguments("me", "me"));
        assert(!(boolean) equals2.invokeWithArguments("me", "thee"));
    }
}
MethodHandle caToString = publicLookup()
  .findStatic(Arrays.class, "toString", methodType(String.class, char[].class));
assertEquals("[A, B, C]", (String) caToString.invokeExact("ABC".toCharArray()));
MethodHandle caString3 = caToString.asCollector(char[].class, 3);
assertEquals("[A, B, C]", (String) caString3.invokeExact('A', 'B', 'C'));
MethodHandle caToString2 = caString3.asSpreader(char[].class, 2);
assertEquals("[A, B, C]", (String) caToString2.invokeExact('A', "BC".toCharArray()));
     * }</pre></blockquote>
     * @param arrayType usually {@code Object[]}, the type of the array argument from which to extract the spread arguments
     * @param arrayLength the number of arguments to spread from an incoming array argument
     * @return a new method handle which spreads its final array argument,
     *         before calling the original method handle
     * @throws NullPointerException if {@code arrayType} is a null reference
     * @throws IllegalArgumentException if {@code arrayType} is not an array type,
     *         or if target does not have at least
     *         {@code arrayLength} parameter types,
     *         or if {@code arrayLength} is negative,
     *         or if the resulting method handle's type would have
     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
     * @see #asCollector
     */
    public MethodHandle asSpreader(Class<?> arrayType, int arrayLength) {
        MethodType postSpreadType = asSpreaderChecks(arrayType, arrayLength);
        int arity = type().parameterCount();
        int spreadArgPos = arity - arrayLength;
        MethodHandle afterSpread = this.asType(postSpreadType);
        BoundMethodHandle mh = afterSpread.rebind();
        LambdaForm lform = mh.editor().spreadArgumentsForm(1 + spreadArgPos, arrayType, arrayLength);
        MethodType preSpreadType = postSpreadType.replaceParameterTypes(spreadArgPos, arity, arrayType);
        return mh.copyWith(preSpreadType, lform);
    }

    /**
     * See if {@code asSpreader} can be validly called with the given arguments.
     * Return the type of the method handle call after spreading but before conversions.
     */
    private MethodType asSpreaderChecks(Class<?> arrayType, int arrayLength) {
        spreadArrayChecks(arrayType, arrayLength);
        int nargs = type().parameterCount();
        if (nargs < arrayLength || arrayLength < 0)
            throw newIllegalArgumentException("bad spread array length");
        Class<?> arrayElement = arrayType.getComponentType();
        MethodType mtype = type();
        boolean match = true, fail = false;
        for (int i = nargs - arrayLength; i < nargs; i++) {
            Class<?> ptype = mtype.parameterType(i);
            if (ptype != arrayElement) {
                match = false;
                if (!MethodType.canConvert(arrayElement, ptype)) {
                    fail = true;
                    break;
                }
            }
        }
        if (match)  return mtype;
        MethodType needType = mtype.asSpreaderType(arrayType, arrayLength);
        if (!fail)  return needType;
        // elicit an error:
        this.asType(needType);
        throw newInternalError("should not return", null);
    }

    private void spreadArrayChecks(Class<?> arrayType, int arrayLength) {
        Class<?> arrayElement = arrayType.getComponentType();
        if (arrayElement == null)
            throw newIllegalArgumentException("not an array type", arrayType);
        if ((arrayLength & 0x7F) != arrayLength) {
            if ((arrayLength & 0xFF) != arrayLength)
                throw newIllegalArgumentException("array length is not legal", arrayLength);
            assert(arrayLength >= 128);
            if (arrayElement == long.class ||
                arrayElement == double.class)
                throw newIllegalArgumentException("array length is not legal for long[] or double[]", arrayLength);
        }
    }

    /**
     * Makes an <em>array-collecting</em> method handle, which accepts a given number of trailing
     * positional arguments and collects them into an array argument.
     * The new method handle adapts, as its <i>target</i>,
     * the current method handle.  The type of the adapter will be
     * the same as the type of the target, except that a single trailing
     * parameter (usually of type {@code arrayType}) is replaced by
     * {@code arrayLength} parameters whose type is element type of {@code arrayType}.
     * <p>
     * If the array type differs from the final argument type on the original target,
     * the original target is adapted to take the array type directly,
     * as if by a call to {@link #asType asType}.
     * <p>
     * When called, the adapter replaces its trailing {@code arrayLength}
     * arguments by a single new array of type {@code arrayType}, whose elements
     * comprise (in order) the replaced arguments.
     * Finally the target is called.
     * What the target eventually returns is returned unchanged by the adapter.
     * <p>
     * (The array may also be a shared constant when {@code arrayLength} is zero.)
     * <p>
     * (<em>Note:</em> The {@code arrayType} is often identical to the last
     * parameter type of the original target.
     * It is an explicit argument for symmetry with {@code asSpreader}, and also
     * to allow the target to use a simple {@code Object} as its last parameter type.)
     * <p>
     * In order to create a collecting adapter which is not restricted to a particular
     * number of collected arguments, use {@link #asVarargsCollector asVarargsCollector} instead.
     * <p>
     * Here are some examples of array-collecting method handles:
     * <blockquote><pre>{@code
MethodHandle deepToString = publicLookup()
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
assertEquals("[won]",   (String) deepToString.invokeExact(new Object[]{"won"}));
MethodHandle ts1 = deepToString.asCollector(Object[].class, 1);
assertEquals(methodType(String.class, Object.class), ts1.type());
//assertEquals("[won]", (String) ts1.invokeExact(         new Object[]{"won"})); //FAIL
assertEquals("[[won]]", (String) ts1.invokeExact((Object) new Object[]{"won"}));
// arrayType can be a subtype of Object[]
MethodHandle ts2 = deepToString.asCollector(String[].class, 2);
assertEquals(methodType(String.class, String.class, String.class), ts2.type());
assertEquals("[two, too]", (String) ts2.invokeExact("two", "too"));
MethodHandle ts0 = deepToString.asCollector(Object[].class, 0);
assertEquals("[]", (String) ts0.invokeExact());
// collectors can be nested, Lisp-style
MethodHandle ts22 = deepToString.asCollector(Object[].class, 3).asCollector(String[].class, 2);
assertEquals("[A, B, [C, D]]", ((String) ts22.invokeExact((Object)'A', (Object)"B", "C", "D")));
// arrayType can be any primitive array type
MethodHandle bytesToString = publicLookup()
  .findStatic(Arrays.class, "toString", methodType(String.class, byte[].class))
  .asCollector(byte[].class, 3);
assertEquals("[1, 2, 3]", (String) bytesToString.invokeExact((byte)1, (byte)2, (byte)3));
MethodHandle longsToString = publicLookup()
  .findStatic(Arrays.class, "toString", methodType(String.class, long[].class))
  .asCollector(long[].class, 1);
assertEquals("[123]", (String) longsToString.invokeExact((long)123));
     * }</pre></blockquote>
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
     * @param arrayLength the number of arguments to collect into a new array argument
     * @return a new method handle which collects some trailing argument
     *         into an array, before calling the original method handle
     * @throws NullPointerException if {@code arrayType} is a null reference
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type,
     *         or {@code arrayLength} is not a legal array size,
     *         or the resulting method handle's type would have
     *         <a href="MethodHandle.html#maxarity">too many parameters</a>
     * @throws WrongMethodTypeException if the implied {@code asType} call fails
     * @see #asSpreader
     * @see #asVarargsCollector
     */
    public MethodHandle asCollector(Class<?> arrayType, int arrayLength) {
        asCollectorChecks(arrayType, arrayLength);
        int collectArgPos = type().parameterCount() - 1;
        BoundMethodHandle mh = rebind();
        MethodType resultType = type().asCollectorType(arrayType, arrayLength);
        MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength);
        LambdaForm lform = mh.editor().collectArgumentArrayForm(1 + collectArgPos, newArray);
        if (lform != null) {
            return mh.copyWith(resultType, lform);
        }
        lform = mh.editor().collectArgumentsForm(1 + collectArgPos, newArray.type().basicType());
        return mh.copyWithExtendL(resultType, lform, newArray);
    }

    /**
     * See if {@code asCollector} can be validly called with the given arguments.
     * Return false if the last parameter is not an exact match to arrayType.
     */
    /*non-public*/ boolean asCollectorChecks(Class<?> arrayType, int arrayLength) {
        spreadArrayChecks(arrayType, arrayLength);
        int nargs = type().parameterCount();
        if (nargs != 0) {
            Class<?> lastParam = type().parameterType(nargs-1);
            if (lastParam == arrayType)  return true;
            if (lastParam.isAssignableFrom(arrayType))  return false;
        }
        throw newIllegalArgumentException("array type not assignable to trailing argument", this, arrayType);
    }

    /**
     * Makes a <em>variable arity</em> adapter which is able to accept
     * any number of trailing positional arguments and collect them
     * into an array argument.
     * <p>
     * The type and behavior of the adapter will be the same as
     * the type and behavior of the target, except that certain
     * {@code invoke} and {@code asType} requests can lead to
     * trailing positional arguments being collected into target's
     * trailing parameter.
     * Also, the last parameter type of the adapter will be
     * {@code arrayType}, even if the target has a different
     * last parameter type.
     * <p>
     * This transformation may return {@code this} if the method handle is
     * already of variable arity and its trailing parameter type
     * is identical to {@code arrayType}.
     * <p>
     * When called with {@link #invokeExact invokeExact}, the adapter invokes
     * the target with no argument changes.
     * (<em>Note:</em> This behavior is different from a
     * {@linkplain #asCollector fixed arity collector},
     * since it accepts a whole array of indeterminate length,
     * rather than a fixed number of arguments.)
     * <p>
     * When called with plain, inexact {@link #invoke invoke}, if the caller
     * type is the same as the adapter, the adapter invokes the target as with
     * {@code invokeExact}.
     * (This is the normal behavior for {@code invoke} when types match.)
     * <p>
     * Otherwise, if the caller and adapter arity are the same, and the
     * trailing parameter type of the caller is a reference type identical to
     * or assignable to the trailing parameter type of the adapter,
     * the arguments and return values are converted pairwise,
     * as if by {@link #asType asType} on a fixed arity
     * method handle.
     * <p>
     * Otherwise, the arities differ, or the adapter's trailing parameter
     * type is not assignable from the corresponding caller type.
     * In this case, the adapter replaces all trailing arguments from
     * the original trailing argument position onward, by
     * a new array of type {@code arrayType}, whose elements
     * comprise (in order) the replaced arguments.
     * <p>
     * The caller type must provides as least enough arguments,
     * and of the correct type, to satisfy the target's requirement for
     * positional arguments before the trailing array argument.
     * Thus, the caller must supply, at a minimum, {@code N-1} arguments,
     * where {@code N} is the arity of the target.
     * Also, there must exist conversions from the incoming arguments
     * to the target's arguments.
     * As with other uses of plain {@code invoke}, if these basic
     * requirements are not fulfilled, a {@code WrongMethodTypeException}
     * may be thrown.
     * <p>
     * In all cases, what the target eventually returns is returned unchanged by the adapter.
     * <p>
     * In the final case, it is exactly as if the target method handle were
     * temporarily adapted with a {@linkplain #asCollector fixed arity collector}
     * to the arity required by the caller type.
     * (As with {@code asCollector}, if the array length is zero,
     * a shared constant may be used instead of a new array.
     * If the implied call to {@code asCollector} would throw
     * an {@code IllegalArgumentException} or {@code WrongMethodTypeException},
     * the call to the variable arity adapter must throw
     * {@code WrongMethodTypeException}.)
     * <p>
     * The behavior of {@link #asType asType} is also specialized for
     * variable arity adapters, to maintain the invariant that
     * plain, inexact {@code invoke} is always equivalent to an {@code asType}
     * call to adjust the target type, followed by {@code invokeExact}.
     * Therefore, a variable arity adapter responds
     * to an {@code asType} request by building a fixed arity collector,
     * if and only if the adapter and requested type differ either
     * in arity or trailing argument type.
     * The resulting fixed arity collector has its type further adjusted
     * (if necessary) to the requested type by pairwise conversion,
     * as if by another application of {@code asType}.
     * <p>
     * When a method handle is obtained by executing an {@code ldc} instruction
     * of a {@code CONSTANT_MethodHandle} constant, and the target method is marked
     * as a variable arity method (with the modifier bit {@code 0x0080}),
     * the method handle will accept multiple arities, as if the method handle
     * constant were created by means of a call to {@code asVarargsCollector}.
     * <p>
     * In order to create a collecting adapter which collects a predetermined
     * number of arguments, and whose type reflects this predetermined number,
     * use {@link #asCollector asCollector} instead.
     * <p>
     * No method handle transformations produce new method handles with
     * variable arity, unless they are documented as doing so.
     * Therefore, besides {@code asVarargsCollector},
     * all methods in {@code MethodHandle} and {@code MethodHandles}
     * will return a method handle with fixed arity,
     * except in the cases where they are specified to return their original
     * operand (e.g., {@code asType} of the method handle's own type).
     * <p>
     * Calling {@code asVarargsCollector} on a method handle which is already
     * of variable arity will produce a method handle with the same type and behavior.
     * It may (or may not) return the original variable arity method handle.
     * <p>
     * Here is an example, of a list-making variable arity method handle:
     * <blockquote><pre>{@code
MethodHandle deepToString = publicLookup()
  .findStatic(Arrays.class, "deepToString", methodType(String.class, Object[].class));
MethodHandle ts1 = deepToString.asVarargsCollector(Object[].class);
assertEquals("[won]",   (String) ts1.invokeExact(    new Object[]{"won"}));
assertEquals("[won]",   (String) ts1.invoke(         new Object[]{"won"}));
assertEquals("[won]",   (String) ts1.invoke(                      "won" ));
assertEquals("[[won]]", (String) ts1.invoke((Object) new Object[]{"won"}));
// findStatic of Arrays.asList(...) produces a variable arity method handle:
MethodHandle asList = publicLookup()
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class));
assertEquals(methodType(List.class, Object[].class), asList.type());
assert(asList.isVarargsCollector());
assertEquals("[]", asList.invoke().toString());
assertEquals("[1]", asList.invoke(1).toString());
assertEquals("[two, too]", asList.invoke("two", "too").toString());
String[] argv = { "three", "thee", "tee" };
assertEquals("[three, thee, tee]", asList.invoke(argv).toString());
assertEquals("[three, thee, tee]", asList.invoke((Object[])argv).toString());
List ls = (List) asList.invoke((Object)argv);
assertEquals(1, ls.size());
assertEquals("[three, thee, tee]", Arrays.toString((Object[])ls.get(0)));
     * }</pre></blockquote>
     * <p style="font-size:smaller;">
     * <em>Discussion:</em>
     * These rules are designed as a dynamically-typed variation
     * of the Java rules for variable arity methods.
     * In both cases, callers to a variable arity method or method handle
     * can either pass zero or more positional arguments, or else pass
     * pre-collected arrays of any length.  Users should be aware of the
     * special role of the final argument, and of the effect of a
     * type match on that final argument, which determines whether
     * or not a single trailing argument is interpreted as a whole
     * array or a single element of an array to be collected.
     * Note that the dynamic type of the trailing argument has no
     * effect on this decision, only a comparison between the symbolic
     * type descriptor of the call site and the type descriptor of the method handle.)
     *
     * @param arrayType often {@code Object[]}, the type of the array argument which will collect the arguments
     * @return a new method handle which can collect any number of trailing arguments
     *         into an array, before calling the original method handle
     * @throws NullPointerException if {@code arrayType} is a null reference
     * @throws IllegalArgumentException if {@code arrayType} is not an array type
     *         or {@code arrayType} is not assignable to this method handle's trailing parameter type
     * @see #asCollector
     * @see #isVarargsCollector
     * @see #asFixedArity
     */
    public MethodHandle asVarargsCollector(Class<?> arrayType) {
        arrayType.getClass(); // explicit NPE
        boolean lastMatch = asCollectorChecks(arrayType, 0);
        if (isVarargsCollector() && lastMatch)
            return this;
        return MethodHandleImpl.makeVarargsCollector(this, arrayType);
    }

    /**
     * Determines if this method handle
     * supports {@linkplain #asVarargsCollector variable arity} calls.
     * Such method handles arise from the following sources:
     * <ul>
     * <li>a call to {@linkplain #asVarargsCollector asVarargsCollector}
     * <li>a call to a {@linkplain java.lang.invoke.MethodHandles.Lookup lookup method}
     *     which resolves to a variable arity Java method or constructor
     * <li>an {@code ldc} instruction of a {@code CONSTANT_MethodHandle}
     *     which resolves to a variable arity Java method or constructor
     * </ul>
     * @return true if this method handle accepts more than one arity of plain, inexact {@code invoke} calls
     * @see #asVarargsCollector
     * @see #asFixedArity
     */
    public boolean isVarargsCollector() {
        return false;
    }

    /**
     * Makes a <em>fixed arity</em> method handle which is otherwise
     * equivalent to the current method handle.
     * <p>
     * If the current method handle is not of
     * {@linkplain #asVarargsCollector variable arity},
     * the current method handle is returned.
     * This is true even if the current method handle
     * could not be a valid input to {@code asVarargsCollector}.
     * <p>
     * Otherwise, the resulting fixed-arity method handle has the same
     * type and behavior of the current method handle,
     * except that {@link #isVarargsCollector isVarargsCollector}
     * will be false.
     * The fixed-arity method handle may (or may not) be the
     * a previous argument to {@code asVarargsCollector}.
     * <p>
     * Here is an example, of a list-making variable arity method handle:
     * <blockquote><pre>{@code
MethodHandle asListVar = publicLookup()
  .findStatic(Arrays.class, "asList", methodType(List.class, Object[].class))
  .asVarargsCollector(Object[].class);
MethodHandle asListFix = asListVar.asFixedArity();
assertEquals("[1]", asListVar.invoke(1).toString());
Exception caught = null;
try { asListFix.invoke((Object)1); }
catch (Exception ex) { caught = ex; }
assert(caught instanceof ClassCastException);
assertEquals("[two, too]", asListVar.invoke("two", "too").toString());
try { asListFix.invoke("two", "too"); }
catch (Exception ex) { caught = ex; }
assert(caught instanceof WrongMethodTypeException);
Object[] argv = { "three", "thee", "tee" };
assertEquals("[three, thee, tee]", asListVar.invoke(argv).toString());
assertEquals("[three, thee, tee]", asListFix.invoke(argv).toString());
assertEquals(1, ((List) asListVar.invoke((Object)argv)).size());
assertEquals("[three, thee, tee]", asListFix.invoke((Object)argv).toString());
     * }</pre></blockquote>
     *
     * @return a new method handle which accepts only a fixed number of arguments
     * @see #asVarargsCollector
     * @see #isVarargsCollector
     */
    public MethodHandle asFixedArity() {
        assert(!isVarargsCollector());
        return this;
    }

    /**
     * Binds a value {@code x} to the first argument of a method handle, without invoking it.
     * The new method handle adapts, as its <i>target</i>,
     * the current method handle by binding it to the given argument.
     * The type of the bound handle will be
     * the same as the type of the target, except that a single leading
     * reference parameter will be omitted.
     * <p>
     * When called, the bound handle inserts the given value {@code x}
     * as a new leading argument to the target.  The other arguments are
     * also passed unchanged.
     * What the target eventually returns is returned unchanged by the bound handle.
     * <p>
     * The reference {@code x} must be convertible to the first parameter
     * type of the target.
     * <p>
     * (<em>Note:</em>  Because method handles are immutable, the target method handle
     * retains its original type and behavior.)
     * @param x  the value to bind to the first argument of the target
     * @return a new method handle which prepends the given value to the incoming
     *         argument list, before calling the original method handle
     * @throws IllegalArgumentException if the target does not have a
     *         leading parameter type that is a reference type
     * @throws ClassCastException if {@code x} cannot be converted
     *         to the leading parameter type of the target
     * @see MethodHandles#insertArguments
     */
    public MethodHandle bindTo(Object x) {
        x = type.leadingReferenceParameter().cast(x);  // throw CCE if needed
        return bindArgumentL(0, x);
    }

    /**
     * Returns a string representation of the method handle,
     * starting with the string {@code "MethodHandle"} and
     * ending with the string representation of the method handle's type.
     * In other words, this method returns a string equal to the value of:
     * <blockquote><pre>{@code
     * "MethodHandle" + type().toString()
     * }</pre></blockquote>
     * <p>
     * (<em>Note:</em>  Future releases of this API may add further information
     * to the string representation.
     * Therefore, the present syntax should not be parsed by applications.)
     *
     * @return a string representation of the method handle
     */
    @Override
    public String toString() {
        if (DEBUG_METHOD_HANDLE_NAMES)  return "MethodHandle"+debugString();
        return standardString();
    }
    String standardString() {
        return "MethodHandle"+type;
    }
    /** Return a string with a several lines describing the method handle structure.
     *  This string would be suitable for display in an IDE debugger.
     */
    String debugString() {
        return type+" : "+internalForm()+internalProperties();
    }

    //// Implementation methods.
    //// Sub-classes can override these default implementations.
    //// All these methods assume arguments are already validated.

    // Other transforms to do:  convert, explicitCast, permute, drop, filter, fold, GWT, catch

    BoundMethodHandle bindArgumentL(int pos, Object value) {
        return rebind().bindArgumentL(pos, value);
    }

    /*non-public*/
    MethodHandle setVarargs(MemberName member) throws IllegalAccessException {
        if (!member.isVarargs())  return this;
        Class<?> arrayType = type().lastParameterType();
        if (arrayType.isArray()) {
            return MethodHandleImpl.makeVarargsCollector(this, arrayType);
        }
        throw member.makeAccessException("cannot make variable arity", null);
    }

    /*non-public*/
    MethodHandle viewAsType(MethodType newType, boolean strict) {
        // No actual conversions, just a new view of the same method.
        // Note that this operation must not produce a DirectMethodHandle,
        // because retyped DMHs, like any transformed MHs,
        // cannot be cracked into MethodHandleInfo.
        assert viewAsTypeChecks(newType, strict);
        BoundMethodHandle mh = rebind();
        assert(!((MethodHandle)mh instanceof DirectMethodHandle));
        return mh.copyWith(newType, mh.form);
    }

    /*non-public*/
    boolean viewAsTypeChecks(MethodType newType, boolean strict) {
        if (strict) {
            assert(type().isViewableAs(newType, true))
                : Arrays.asList(this, newType);
        } else {
            assert(type().basicType().isViewableAs(newType.basicType(), true))
                : Arrays.asList(this, newType);
        }
        return true;
    }

    // Decoding

    /*non-public*/
    LambdaForm internalForm() {
        return form;
    }

    /*non-public*/
    MemberName internalMemberName() {
        return null;  // DMH returns DMH.member
    }

    /*non-public*/
    Class<?> internalCallerClass() {
        return null;  // caller-bound MH for @CallerSensitive method returns caller
    }

    /*non-public*/
    MethodHandleImpl.Intrinsic intrinsicName() {
        // no special intrinsic meaning to most MHs
        return MethodHandleImpl.Intrinsic.NONE;
    }

    /*non-public*/
    MethodHandle withInternalMemberName(MemberName member, boolean isInvokeSpecial) {
        if (member != null) {
            return MethodHandleImpl.makeWrappedMember(this, member, isInvokeSpecial);
        } else if (internalMemberName() == null) {
            // The required internaMemberName is null, and this MH (like most) doesn't have one.
            return this;
        } else {
            // The following case is rare. Mask the internalMemberName by wrapping the MH in a BMH.
            MethodHandle result = rebind();
            assert (result.internalMemberName() == null);
            return result;
        }
    }

    /*non-public*/
    boolean isInvokeSpecial() {
        return false;  // DMH.Special returns true
    }

    /*non-public*/
    Object internalValues() {
        return null;
    }

    /*non-public*/
    Object internalProperties() {
        // Override to something to follow this.form, like "\n& FOO=bar"
        return "";
    }

    //// Method handle implementation methods.
    //// Sub-classes can override these default implementations.
    //// All these methods assume arguments are already validated.

    /*non-public*/
    abstract MethodHandle copyWith(MethodType mt, LambdaForm lf);

    /** Require this method handle to be a BMH, or else replace it with a "wrapper" BMH.
     *  Many transforms are implemented only for BMHs.
     *  @return a behaviorally equivalent BMH
     */
    abstract BoundMethodHandle rebind();

    /**
     * Replace the old lambda form of this method handle with a new one.
     * The new one must be functionally equivalent to the old one.
     * Threads may continue running the old form indefinitely,
     * but it is likely that the new one will be preferred for new executions.
     * Use with discretion.
     */
    /*non-public*/
    void updateForm(LambdaForm newForm) {
        assert(newForm.customized == null || newForm.customized == this);
        if (form == newForm)  return;
        newForm.prepare();  // as in MethodHandle.<init>
        UNSAFE.putObject(this, FORM_OFFSET, newForm);
        UNSAFE.fullFence();
    }

    /** Craft a LambdaForm customized for this particular MethodHandle */
    /*non-public*/
    void customize() {
        if (form.customized == null) {
            LambdaForm newForm = form.customize(this);
            updateForm(newForm);
        } else {
            assert(form.customized == this);
        }
    }

    private static final long FORM_OFFSET;
    static {
        try {
            FORM_OFFSET = UNSAFE.objectFieldOffset(MethodHandle.class.getDeclaredField("form"));
        } catch (ReflectiveOperationException ex) {
            throw newInternalError(ex);
        }
    }
}
